/**
 * @description courseModel Service
 */

const {
  courseModel,
  UserModel
} = require('../db/index')
const Op = require('sequelize').Op

async function addData(params) {
  let item = await courseModel.findAll({
    where: {
      name: params.name
    }
  })
  if (item.length) {
    return 'error'
  }
  const result = await courseModel.create(params)
  const data = result.dataValues
  return data
}

async function updateData(
  params,
  id
) {
  // 拼接修改内容
  const updateObj = params

  // 拼接查询条件
  const whereOption = {}
  if (id) {
    whereOption.id = id
  }
  // 执行修改
  const result = await courseModel.update(updateObj, {
    where: whereOption
  })
  return result[0] > 0
}

async function deleteData(id) {
  const result = await courseModel.destroy({
    where: {
      id
    }
  })
  return result > 0
}

async function queryByNo(no) {
  const result = await courseModel.findAll({
    where: {
      no
    }
  })
  return {
    exsit: !!result.length
  }
}

async function queryAll(params) {
  try {
    const {
      page = 1,
      pageSize = 10, 
      type,
      key
    } = params
    if (page < 1) {
      page = 1
    }
    const whereOption = {}
    console.log(key)
    if (key) {
      whereOption[Op.or] = [
        { name: { [Op.like]: `%${key}%` } },
        { type: { [Op.like]: `%${key}%` } },
        { fileList: { [Op.like]: `%${key}%` } },
      ];
    }
    if (type) {
      whereOption.type = type
    }
    console.log(whereOption)
    const result = await courseModel.findAll({
      include: [
        {
          model: UserModel
        }
      ],
      limit: pageSize,
      offset: (page - 1) * pageSize,
      where: whereOption
    })
    const total = await courseModel.findAll({
      where: whereOption
    })
    return {
      page,
      pageSize,
      total: total.length || 0,
      data: result || []
    }
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  addData,
  updateData,
  deleteData,
  queryAll,
  queryByNo
}